<?php
/**
 * Created by PhpStorm.
 * User: yxs
 * Date: 2017/6/30
 * Time: 15:33
 */

namespace app\order\controller;

use icontroller\wechat\AController;
use library\common\str;
use library\common\wechat_msg\send_msg;
use library\order\format;
use library\tencent\wechat\admin_wechat\SendTemplateMessage;
use library\tencent\wechat\wechat_index\PayManagement;
use model\Account;
use model\AccountBill;
use model\AccountPayment;
use model\AccountRole;
use model\AccountWechat;
use model\ShopGoodsVariant;
use model\ShopOrderItem;
use model\ShopUserAddress;
use model\ShopUserCart;
use model\ShopGoods;
use model\ShopStore;
use model\ShopOrder;

use model\ShopOrderGoods;
use think\Db;
use think\Request;

class Order extends AController
{
    public function index()
    {
        $request = Request::instance();
        if ($request->isAjax()) {
            $page = input('page', 0);                      //分页
            $count = config('paginate.list_rows');        //每页数量
            $flag_pay = input("flag_pay");
            $flag_status = input("flag_status", null);
            $flag_delivery = input("flag_delivery");
            $mo = new ShopOrder();
            $where = [
                "account_id" => $this->account_id
            ];
            if ($flag_pay != null) {
                $where["flag_pay"] = $flag_pay;
            }
            if ($flag_status != null && $flag_status != 4) {
                $where["flag_status"] = $flag_status;
            } else {
                $where["flag_status"] = ["<>", 4];
            }
            if ($flag_delivery != null) {
                $where["flag_delivery"] = $flag_delivery;
            }

            if ($flag_status == "0") {
                $where["flag_status"] = ["in", [0, 5]];
                $where["flag_delivery|flag_pay"] = 1;
            }
            if ($flag_status == 1) {
                $where["flag_status"] = ["in", [1, 6]];
            }

            $list = $mo->where($where)->page($page, $count)->order(["op_time" => "desc"])->select();
            $d_list = $list;

            foreach ($list as $ik => $iv) {
                $item_list = ShopOrderItem::all(["order_id" => $iv["id"]]);
                $order_item = [];
                $d_list[$ik]["send_status"] = ["code" => 1, "msg" => ""];
                foreach ($item_list as $k => $v) {
                    if ($v->shopStore["flag_lock"] == 1 || !str::time_quantum($v->shopStore["bizhours_start"], $v->shopStore["bizhours_end"])) {
                        $d_list[$ik]["send_status"] = ["code" => 0, "msg" => "店家{$v->shopStore["name"]}歇业中，请稍后支付"];
                    }
                    $order_item[] = [
                        "store_name" => $v->shopStore->name,
                        "logo" => $v->shopStore->logo,
                        "pay_amount" => $v->pay_amount
                    ];
                }
                $d_list[$ik]["order_items"] = $order_item;
            }
//            foreach ($list as $k => $v) {
//                $shopGoods = [];
//                $d_list[$k]->shopStore = $v->shopStore;
//                foreach ($v->shopOrderGoods as $k1 => $v1) {
//                    $name = $v1->shopGoods->name;
//                    if ($v1->variant_id > 0) {
//                        $variant = ShopGoodsVariant::get($v1->variant_id);
//                        $name = $name . "(" . $variant->name . ")";
//                    }
//                    $shopGoods[] = [
//                        "name" => $name,
//                        "cover_image" => $v1->shopGoods->cover_image,
//                        "quantity" => $v1->quantity,
//                        "amount" => $v1->amount
//                    ];
//                }
//                $d_list[$k]->shopGoods = $shopGoods;
//            }
            $this->success("获取数据成功!", null, $d_list);
        }

        return view();
    }

    public function detail()
    {
        $order_id = input("order_id");
        $this->assign("order_id", $order_id);
        $this->assign("back_url", url("/order/Order/index"));
        return view();
    }

    public function detail_data()
    {

        $order_id = input("order_id");
        $list = ShopOrderItem::all(["order_id" => $order_id]);
        $d_list = $list;
        //配送信息
        $info = ShopOrder::get($order_id);
        if ($info) {
            $info = $info->getData();
        }
        $info["send_status"] = ["code" => 1, "msg" => ""];
        foreach ($list as $k => $v) {
            $shopGoods = [];
            if ($v->shopStore["flag_lock"] == 1 || !str::time_quantum($v->shopStore["bizhours_start"], $v->shopStore["bizhours_end"])) {
                $info["send_status"] = ["code" => 0, "msg" => "店家{$v->shopStore["name"]}歇业中，请稍后支付"];
            }
            $d_list[$k]->shopStore = $v->shopStore;
            foreach ($v->shopOrderGoods as $k1 => $v1) {
                $name = $v1->shopGoods->name;
                $add_flag = true;
                $price = $v1->shopGoods->price;
                if ($v1->variant_id > 0) {
                    $variant = ShopGoodsVariant::get($v1->variant_id);
                    if ($variant) {
                        $name = $name . "(" . $variant->name . ")";
                        $price = $variant->price;
                    }
                    if (!$variant || $variant->flag_delete == 1) {
                        $add_flag = false;
                    }
                }

                if ($v1->shopGoods->flag_putaway == 0 || $v1->shopGoods->flag_delete == 1) {
                    $add_flag = false;
                }
                if ($v->flag_pay == 0 && $v->flag_status['value'] == 0 && $v->flag_delivery != 1) {//立即支付
                    if ($add_flag) {
                        $shopGoods[] = [
                            "name" => $name,
                            "quantity" => $v1->quantity,
                            "amount" => $price
                        ];
                    }
                } else {
                    $shopGoods[] = [
                        "name" => $name,
                        "quantity" => $v1->quantity,
                        "amount" => $price
                    ];
                }
            }
            $d_list[$k]->shopGoods = $shopGoods;
        }

        $info["flag_status_text"] = format::order_status($info["flag_status"]);
        $this->success("获取数据成功!", null, ["list" => $d_list, "info" => $info]);
    }

    // <editor-fold defaultstate="collapsed" desc="提交订单">
    public function send_order()
    {
        $data = input("data");//"1,2,3"购物车id
        $add_data = [];
        $view_data = [];
        $goods_item = [];
        $total_price = 0;
        $store_total_price = [];

        $list = ShopUserCart::all(["id" => ["in", $data], "account_id" => $this->account_id]);
        $request = Request::instance();
        $current_url = $request->url();
        //添加购物车
        foreach ($list as $v) {
            $add_data[] = [
                "account_id" => $this->account_id,
                "goods_id" => $v["goods_id"],
                "quantity" => $v["quantity"]
            ];

            $good = ShopGoods::get($v["goods_id"]);
            if ($good->flag_delete != 1 && $good->flag_putaway != 0) {
                $ss = ShopStore::get($good->store_id);
                $price = $good->price;
                $add_flag = true;
                if ($v->variant_id > 0) {
                    $sc = ShopGoodsVariant::get($v->variant_id);
                    if ($sc && $sc->flag_delete == 0) {
                        $price = $sc->price;
                        $good->price = $sc->price;
                        $good->name = $good->name . "(" . $sc->name . ")";
                    } else {
                        $add_flag = false;
                    }
                }
                if ($add_flag) {
                    $total_price += bcmul($price, $v["quantity"], 2);
                    $total_price = number_format($total_price, 2, '.', '');
                    $good["num"] = $v["quantity"];
                    if (key_exists($ss["id"], $store_total_price)) {
                        $store_total_price[$ss["id"]] += bcmul($price, $v["quantity"], 2);
                    } else {
                        $store_total_price[$ss["id"]] = bcmul($price, $v["quantity"], 2);
                    }
                    $store_total_price[$ss["id"]] = number_format($store_total_price[$ss["id"]], 2, '.', '');
                    $goods_item[$ss["id"]][] = $good;
                    $view_data[$ss["id"]] = [
                        "name" => $ss["name"],
                        "logo" => $ss["logo"],
                        "total_price" => $store_total_price[$ss["id"]],
                        "items" => $goods_item[$ss["id"]]
                    ];
                }
            }
        }
        //获取默认地址
        $user_address = ShopUserAddress::get(["account_id" => $this->account_id, "flag_default" => 1]);
        if (!$user_address) {
            $user_address = ShopUserAddress::get(["account_id" => $this->account_id]);
        }
        $this->assign("url", $current_url);
        $this->assign("cart_ids", $data);
        $this->assign("user_address", $user_address);
        $this->assign("total_price", $total_price);
        $this->assign("list", $view_data);
        return view();
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="确认订单">
    public function add_order()
    {
        $cart_ids = input("cart_ids");//"1,2,3"购物车id
        $address_id = input("address_id");
        $remark = input("remark");
        $shop_order = [];
        $list = ShopUserCart::all($cart_ids);
        if (empty($list)) {
            $this->error("请不要重复提交订单!");
        }
        if (empty($address_id)) {
            $o_address = input("o_address");
            $o_mobile = input("o_mobile");
//            if (empty($o_mobile) || empty($o_address)) {
//                $this->error("请输入地址和联系方式");
//            }
            $o_province = input("o_province");
            $o_city = input("o_city");
            $o_district = input("o_district");
            $o_lng = input("o_lng");
            $o_lat = input("o_lat");
            $o_zoom = input("o_zoom");
            $o_zipcode = input("o_zipcode");
            $o_name = input("o_name");
            $ac_mo = new Account();
            if (empty($o_name)) {
                $o_name = $ac_mo->where(["id" => $this->account_id])->value("name");
            }
        } else {
            $address = ShopUserAddress::get($address_id);
            if (!$address) {
                $this->error("请输入地址和联系方式");
            }
            $o_province = $address->province;
            $o_address = $address->address;
            $o_mobile = $address->mobile;
            $o_city = $address->city;
            $o_district = $address->district;
            $o_name = $address->name;
            $o_lng = $address->lng;
            $o_lat = $address->lat;
            $o_zoom = $address->zoom;
            $o_zipcode = $address->zip_code;
        }
        $shop_order["account_id"] = $this->account_id;
        $shop_order["o_province"] = $o_province;
        $shop_order["o_address"] = $o_address;
        $shop_order["o_mobile"] = $o_mobile;
        $shop_order["o_city"] = $o_city;
        $shop_order["o_district"] = $o_district;
        $shop_order["o_name"] = $o_name;
        $shop_order["o_lng"] = $o_lng;
        $shop_order["o_lat"] = $o_lat;
        $shop_order["o_zoom"] = $o_zoom;
        $shop_order["o_zipcode"] = $o_zipcode;
        $shop_order["remark"] = $remark;

        $add_data = [];
        $goods_item = [];
        $store_total_price = [];
        $store_total_num = [];
        $total_price = 0;
        $total_num = 0;
        foreach ($list as &$v) {
            $good = ShopGoods::get($v->goods_id);
            $good["num"] = $v["quantity"];
            $total_num += $v["quantity"];
            if ($good->flag_delete != 1 && $good->flag_putaway != 0) {
                $ss = ShopStore::get($good->store_id);
                if ($ss["flag_lock"] == 1 || !str::time_quantum($ss["bizhours_start"], $ss["bizhours_end"])) {
                    $this->error("店家{$ss->name}歇业中，请稍后下单");
                    $item["is_work"] = 0; //歇业中
                } else {
                    $item["is_work"] = 1; //营业中
                }
                if ($v->cart_price != $good->price) {
                    $good->price = $v->cart_price;
                }

                $good->variant_id = $v->variant_id;
                $goods_item[$ss["id"]][] = $good;

                $t_price = bcmul($good->price, $v["quantity"], 2);

                $total_price += $t_price;
                $total_price = sprintf('%.2f', $total_price);

                if (key_exists($good->store_id, $store_total_price)) {
                    $store_total_price[$good->store_id] += $t_price;
                } else {
                    $store_total_price[$good->store_id] = $t_price;
                }
                if (key_exists($good->store_id, $store_total_num)) {
                    $store_total_num[$good->store_id] += $v["quantity"];
                } else {
                    $store_total_num[$good->store_id] = $v["quantity"];
                }

                $store_total_price[$ss["id"]] = sprintf('%.2f', $store_total_price[$ss["id"]]);
                $add_data[$ss["id"]] = [
                    "store_id" => $ss["id"],
                    "name" => $ss["name"],
                    "logo" => $ss["logo"],
                    "total_price" => $store_total_price[$good->store_id],
                    "total_num" => $store_total_num[$good->store_id],
                    "items" => $goods_item[$ss["id"]]
                ];
            }
        }
        $shop_order["order_amount"] = $total_price;
        $shop_order["pay_amount"] = $total_price;
        $shop_order["total_amount"] = $total_price;
        $shop_order["goods_quantity"] = $total_num;

        $so = new ShopOrder();
        Db::startTrans();
        $result = $so->validate(true)->save($shop_order);
        if ($result) {
            foreach ($add_data as $vo) {
                $data = [
                    "account_id" => $this->account_id,
                    "order_id" => $so->id,
                    "order_amount" => $vo["total_price"],
                    "pay_amount" => $vo["total_price"],
                    "total_amount" => $vo["total_price"],
                    "goods_quantity" => $vo["total_num"],
                    "o_province" => $o_province,
                    "o_city" => $o_city,
                    "o_district" => $o_district,
                    "o_address" => $o_address,
                    "o_name" => $o_name,
                    "o_mobile" => $o_mobile,
                    "o_lng" => $o_lng,
                    "o_lat" => $o_lat,
                    "o_zoom" => $o_zoom,
                    "o_zipcode" => $o_zipcode,
                    "store_id" => $vo["store_id"],
                    "remark" => $remark
                ];
                $sim = new ShopOrderItem();
                $item = $sim->save($data);
                if (!$item) {
                    Db::rollback();
                    $this->error("提交订单出错，请稍后重试!");
                }
                foreach ($vo["items"] as $g) {
                    if ($item) {
                        $good_data = [
                            "order_item_id" => $sim->id,
                            "goods_id" => $g->id,
                            "quantity" => $g->num,
                            "price" => $g->price,
                            "variant_id" => $g->variant_id,
                            "amount" => bcmul($g->price, $g->num, 2)
                        ];
                        $gim = new ShopOrderGoods();
                        $r = $gim->save($good_data);
                        if (!$r) {
                            $this->error("添加订单出错3");
                        }
                    }
                }
            }
        } else {
            Db::rollback();
            $this->error($so->getError());
        }
        $result = ShopUserCart::destroy($cart_ids);
        if (!$result) {
            Db::rollback();
            $this->error("提交订单出错，请稍后重试!");
        }
        Db::commit();
        $this->success("添加订单成功", null, ["order_id" => $so->id]);
    }

    // </editor-fold>

    public function pay()
    {
        $order_id = input("order_id");
        $this->assign("order_id", $order_id);
        return view();
    }

    public function pay_data(){
        $order_id = input("order_id");
        $request = Request::instance();
        if ($request->isAjax()) {
            if (!empty($order_id)) {
                $order = ShopOrder::get(["id" => $order_id, "account_id" => $this->account_id]);
                if (!$order) {
                    $this->error("获取订单错误2!");
                }
                $info = Account::getField("money,frozen_money,pay_password", ["id" => $this->account_id]);
                $this->success("获取成功！", null, ["info" => $info, "order" => $order]);
            } else {
                $this->error("获取订单错误1!");
            }
        }
    }


    public function order_item_pay()
    {
        $order_id = input("order_item_id");
        if (!empty($order_id)) {
            $order = ShopOrderItem::get(["id" => $order_id, "account_id" => $this->account_id]);
            if (!$order) {
                $this->error("获取订单错误2!");
            }

            $info = Account::getField("money,frozen_money", ["id" => $this->account_id]);
            $this->assign("info", $info);
            $this->assign("order_item", $order);
        } else {
            $this->error("获取订单错误1!");
        }
        return view();
    }

    // <editor-fold defaultstate="collapsed" desc="总订单余额支付">
    public function balance_pay()
    {
        $param = array(
            'pay_password' => input('pay_password'),
            'order_id' => input('order_id')
        );
        //验证支付密码是否正确
        $ac = Account::get($this->account_id);
        $accountBill = new AccountBill();
        if ($ac->pay_password == null) {
            $this->error("您未设置支付密码，请先设置支付密码。", url("user/Account/set_pwd"), -2);
        }
        if (md5($param['pay_password']) != $ac->pay_password) {
            $this->error("支付密码错误");
        }

        $account_money = $ac->money;
        $so_item = new ShopOrderItem();
        $order = ShopOrder::get(["id" => $param["order_id"], "account_id" => $this->account_id]);
        if (!$order) {
            $this->error("获取订单错误2!");
        }
        if (!empty($order->flag_pay)) {
            $this->error("请不要重复提交支付!");
        }
        if ($account_money < $order->order_amount) {
            $this->error('余额不足，请先充值', url("user/Account/recharge"), -1);
        }
        if (!empty($order->flag_pay)||$order->flag_delivery == 1||!empty($order->payment_id)) {
            $this->error("请不要重复提交支付!");
        }

        $order_item_ids = $so_item->where(['account_id' => $this->account_id, 'order_id' => $param["order_id"], 'flag_pay' => 0])->column("id");
        $ac_money = bcsub($account_money,$order->order_amount,2) ;
        Db::startTrans();
        //账户余额扣除
        if ($ac_money>=0) {
            $ac->money = $ac_money;
            $res1 = $ac->save();
            if (!$res1) {
                Db::rollback();
                $this->error('数据出错2，请稍后再试');
            }
        }

        $pay_time = time();
        $goods = [];
        foreach ($order_item_ids as $id) {
            $order_item = ShopOrderItem::get($id);
            if ($order_item) {
                //$order_item->payment_id = $res2->id;
                $order_item->flag_pay = 1;
                $order_item->pay_time = $pay_time;
                $res3 = $order_item->save();
                if (!$res3) {
                    Db::rollback();
                    $this->error('数据出错4，请稍后再试');
                }

                $shopOrderGoods = new ShopOrderGoods();
                $shopGoods = new ShopGoods();
                $goods_id = $shopOrderGoods->where(["order_item_id" => $order_item->id])->column("goods_id");
                $gn = $shopGoods->where(["id" => ["in", $goods_id]])->column("name");
                $goods = array_merge($goods, $gn);
            }
        }
        //更新payment记录
        $data2 = array(
            'pay_type' => 5,
            'pay_time' => $pay_time,
            'flag_pay' => 1,
            'flag_lock' => 1,
            'remark' => "订单($order->order_sn)余额支付",
            "account_id" => $order->account_id,
            "pay_no" => $order->order_sn,
            "pay_money" => $order->pay_amount
        );

        $res2 = AccountPayment::create($data2);
        if (!$res2) {
            Db::rollback();
            $this->error('数据出错3，请稍后再试');
        }
        $order->payment_id = $res2->id;
        $order->flag_pay = 1;
        $order->pay_time = $pay_time;
        $result = $order->save();
        if (!$result) {
            Db::rollback();
            $this->error("提交订单出错2!");
        }
        // 插入钱帐记录
        $data3 = ['account_id' => $this->account_id, 'money' => 0 - $order->order_amount, 'remark' => "订单{$order->order_sn}-余额支付"];
        $res3 = $accountBill->save($data3);
        if (!$res3) {
            Db::rollback();
            $this->error('数据出错3，请稍后再试');
        }

        Db::commit();
        //事务成功，调用微信模板消息接口,返回数据
        //调用微信模板消息接口
        $accountWechat = new AccountWechat();
        $ar = new AccountRole();
        $acc_ids = $ar->where(["role_id" => 2, "flag_delete" => 0])->column("account_id");
        $oauths = $accountWechat->where(["account_id" => ["in", $acc_ids]])->column("openid");
        send_msg::dispatching_msg($oauths, $order, $goods);

        //返回数据
        $this->success("支付成功");
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="子订单余额支付">
    public function balance_item_pay()
    {
        $order_item_id = input("order_item_id");
        $pay_password = input("pay_password");
        $so_item = new ShopOrderItem();
        //验证支付密码是否正确
        $accountBill = new AccountBill();
        $ac = Account::get($this->account_id);
        if ($ac->pay_password == null) {
            $this->error("未设置支付密码，请先设置支付密码。", url("user/Account/set_pwd"), -2);
        }
        if (md5($pay_password) != $ac->pay_password) {
            $this->error("支付密码错误");
        }

        $account_money = $ac->money;
        if (!empty($order_item_id)) {
            $order_item = ShopOrderItem::get(["id" => $order_item_id, "account_id" => $this->account_id]);
            if (!$order_item) {
                $this->error("获取订单错误2!");
            }
            if ($order_item->flag_status['value'] == 4) {
                $this->error("此订单已取消!");
            }
            if (!empty($order_item->payment_id)) {
                $this->error("请不要重复提交支付!");
            }
            if ($order_item->flag_delivery == 1) {
                $this->error("请不要重复提交支付!");
            }
            if ($account_money < $order_item->order_pay) {
                $this->error('余额不足，请先充值', url("user/Account/recharge"), -1);
            }
            $ac_money = bcsub($account_money,$order_item->order_amount,2);
            Db::startTrans();
            //账户余额扣除
            if ($ac_money>=0) {
                $ac->money = $ac_money;
                $res1 = $ac->save();
                if (!$res1) {
                    Db::rollback();
                    $this->error('数据出错2，请稍后再试');
                }
            }

            $pay_time = time();
            if ($order_item) {
                $goods = [];
                //更新payment记录
                $data2 = array(
                    'pay_type' => 5,
                    'pay_time' => $pay_time,
                    'flag_pay' => 1,
                    'flag_lock' => 1,
                    'remark' => "订单($order_item->order_sn)余额支付",
                    "account_id" => $order_item->account_id,
                    "pay_no" => $order_item->order_sn,
                    "pay_money" => $order_item->pay_amount
                );

                $res2 = AccountPayment::create($data2);
                if (!$res2) {
                    Db::rollback();
                    $this->error('数据出错3，请稍后再试');
                }
                $order_item->payment_id = $res2->id;
                $order_item->flag_pay = 1;
                $order_item->pay_time = $pay_time;
                $res3 = $order_item->save();
                if (!$res3) {
                    Db::rollback();
                    $this->error('数据出错4，请稍后再试');
                }

                $count = $so_item->where(["order_id" => $order_item->order_id, "flag_pay" => 1])->count();
                if ($count == 0) {
                    $res4 = ShopOrder::update(["flag_pay" => 1, "pay_time" => $pay_time], ["id" => $order_item->order_id]);
                    if (!$res4) {
                        Db::rollback();
                        $this->error('数据出错5，请稍后再试');
                    }
                }

                $data = array(
                    'account_id' => $this->account_id, 'money' => 0 - $order_item['order_amount'], 'remark' => "订单{$order_item->order_sn}-余额支付"
                );
                $res = AccountBill::create($data);
                if (!$res) {
                    Db::rollback();
                    $this->error('数据出错6，请稍后再试');
                }

                $order_item->flag_pay = 1;
                $order_item->pay_time = $pay_time;
                $order_item->save();
                // 插入钱帐记录
                $res3 = $accountBill->save(['account_id' => $this->account_id, 'money' => 0 - $order_item->pay_amount, 'remark' => '外卖消费']);
                if (!$res3) {
                    Db::rollback();
                    $this->error('数据出错3，请稍后再试');
                }
                //事务成功，调用微信模板消息接口,返回数据
                //调用微信模板消息接口
                //               $oauth = AccountWechat::get(['account_id' => $this->account_id]);
//                $openid = $oauth['openid'];
//                $msg_data = array(
//                    'touser' => $openid,
//                    'keyword1' => $order_item->order_sn,
//                    'keyword2' => "余额支付成功",
//                    'keyword3' => date('Y-m-d', $pay_time),
//                    'keyword4' => "外卖",
//                    'keyword5' => $order_item->pay_amount . '元'
//                );
//                SendTemplateMessage::send_message("OPENTM204987032", $msg_data);
                //               send_msg::pay_suc_msg($openid,$order_item);
                $shopOrderGoods = new ShopOrderGoods();
                $shopGoods = new ShopGoods();
                $accountWechat = new AccountWechat();
                $ar = new AccountRole();
                $goods_id = $shopOrderGoods->where(["order_item_id" => $order_item->id])->column("goods_id");
                $gn = $shopGoods->where(["id" => ["in", $goods_id]])->column("name");
                $goods = array_merge($goods, $gn);
                $acc_ids = $ar->where(["role_id" => 2, "flag_delete" => 0])->column("account_id");

                $oauths = $accountWechat->where(["account_id" => ["in", $acc_ids]])->column("openid");
                send_msg::dispatching_msg($oauths, $order_item, $goods);

            }
            Db::commit();

        }
        //返回数据
        $this->success("支付成功");
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="总订单货到付款">
    public function delivery_pay()
    {
        $order_id = input("order_id");
        if (!empty($order_id)) {
            $order = ShopOrder::get(["id" => $order_id, "account_id" => $this->account_id]);
            if (!$order) {
                $this->error("获取订单错误2!");
            }
            if ($order->flag_status['value'] == 4) {
                $this->error("此订单已取消!");
            }
            if (!empty($order->payment_id)) {
                Db::rollback();
                $this->error("请不要重复提交订单!");
            }
            $order_items = ShopOrderItem::all(["order_id" => $order_id, "account_id" => $this->account_id]);
            $goods = [];
            $shopOrderGoods = new ShopOrderGoods();
            $shopGoods = new ShopGoods();
            Db::startTrans();
            foreach ($order_items as $v) {
                $result = $v->save(["flag_status" => 5, "flag_delivery" => 1]);
                if (!$result) {
                    Db::rollback();
                    $this->error("提交订单出错2!");
                }

                $goods_id = $shopOrderGoods->where(["order_item_id" => $v->id])->column("goods_id");
                $gn = $shopGoods->where(["id" => ["in", $goods_id]])->column("name");
                $goods = array_merge($goods, $gn);
            }
            $data = [
                "account_id" => $this->account_id,
                "pay_type" => 6,
                "pay_no" => $order->order_sn,
                "pay_time" => time(),
                "pay_money" => $order->total_amount,
                "remark" => "订单($order->order_sn)货到付款"
            ];

            $res2 = AccountPayment::create($data);
            if (!$res2) {
                Db::rollback();
                $this->error("提交订单出错1!");
            }
            $order->payment_id = $res2->id;
            $order->flag_status = 5;
            $order->flag_delivery = 1;
            $result = $order->save();
            if (!$result) {
                Db::rollback();
                $this->error("提交订单出错2!");
            }

            Db::commit();
            $accountWechat = new AccountWechat();
            $ar = new AccountRole();
            $acc_ids = $ar->where(["role_id" => 2, "flag_delete" => 0])->column("account_id");
            $oauths = $accountWechat->where(["account_id" => ["in", $acc_ids]])->column("openid");
            send_msg::dispatching_msg($oauths, $order, $goods);
            $this->success("提交订单成功,请等待配送!");
        } else {
            $this->error("获取订单错误1!");
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="子订单货到付款">
    public function delivery_item_pay()
    {
        $order_item_id = input("order_item_id");
        if (!empty($order_item_id)) {
            $so = new ShopOrderItem();
            $order = ShopOrderItem::get(["id" => $order_item_id, "account_id" => $this->account_id]);
            if (!$order) {
                $this->error("获取订单错误2!");
            }
            if ($order->flag_status['value'] == 4) {
                $this->error("此订单已取消!");
            }
            if (!empty($order->payment_id)) {
                $this->error("请不要重复提交订单!");
            }
            $data = [
                "account_id" => $this->account_id,
                "pay_type" => 6,
                "pay_no" => $order->order_sn,
                "pay_time" => time(),
                "pay_money" => $order->total_amount,
                "remark" => "子订单($order->order_sn)货到付款"
            ];


            Db::startTrans();
            $result = AccountPayment::create($data);
            if (!$result) {
                Db::rollback();
                $this->error("提交订单出错1!");
            }
            $result = $order->save(["flag_status" => 5, "payment_id" => $result->id, "flag_delivery" => 1], ["id" => $order_item_id, "account_id" => $this->account_id]);
            if (!$result) {
                Db::rollback();
                $this->error("提交订单出错2!");
            }

            $count = $so->where(["order_id" => $order->order_id, "flag_pay" => 1])->count();
            if ($count == 0) {
                $res5 = ShopOrder::update(["flag_status" => 5, "flag_delivery" => 1], ["id" => $order->order_id]);
                if (!$res5) {
                    Db::rollback();
                    $this->error('数据出错5，请稍后再试');
                }
            }
            Db::commit();
            $shopOrderGoods = new ShopOrderGoods();
            $shopGoods = new ShopGoods();
            $goods_id = $shopOrderGoods->where(["order_item_id" => $order->id])->column("goods_id");
            $goods = $shopGoods->where(["id" => ["in", $goods_id]])->column("name");


            $accountWechat = new AccountWechat();
            //  $oauth = AccountWechat::get(['account_id' => $this->account_id]);
            // $openid = $oauth['openid'];
            $ar = new AccountRole();
            $acc_ids = $ar->where(["role_id" => 2, "flag_delete" => 0])->column("account_id");
            $oauths = $accountWechat->where(["account_id" => ["in", $acc_ids]])->column("openid");
            send_msg::dispatching_msg($oauths, $order, $goods);
            $this->success("提交订单成功,请等待配送!");
        } else {
            $this->error("获取订单错误1!");
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="总订单微信支付">
    public function order_wechat_pay()
    {
        $order_id = input('order_id', 0);
        $aw = new AccountWechat();
        $wechat = $aw->where(['account_id' => $this->account_id])->find();
        $openid = $wechat->openid;
//      $openid="oy2HRv8Pak3uXD1ya-Q3V9wbEONw";


        if ($order_id > 0) {
            $order = ShopOrder::get($order_id);
            if (!$order) {
                $this->error("此订单不存在!");
            }
            if ($order->flag_delivery == 1) {
                $this->error("请不要重复提交支付!");
            }
            $body = "订单{$order->order_sn}提交微信支付";
            $order_num = $order->order_sn;
            $total_fee = $order->order_amount * 100;
            $spbill_create_ip = $this->request->ip();
            $pay = PayManagement::instance();
            $params = array(
                'openid' => $openid,
                'body' => $body,
                'out_trade_no' => $order_num,
                'spbill_create_ip' => $spbill_create_ip,
                'total_fee' => $total_fee,
                'attach' => 3
            );

            $res = $pay->unifiedOrder($params);
            $jsApiParameters = $pay->getJsPayParameters($res['prepay_id']);
            $this->success("提交订单成功!", null, $jsApiParameters);
        }

    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="子订单微信支付">
    public function order_item_wechat_pay()
    {
        $order_item_id = input('order_item_id', 0);
        $aw = new AccountWechat();
        $wechat = $aw->where(['account_id' => $this->account_id])->find();
        $openid = $wechat->openid;
//      $openid="oy2HRv8Pak3uXD1ya-Q3V9wbEONw";
        $body = '';
        $order_item = ShopOrderItem::get($order_item_id);
        if (!$order_item) {
            $this->error("提交支付出错，请稍后重试!");
        }
        if (!empty($order_item->payment_id || $order_item->flag_delivery == 1)) {
            $this->error("请不要重复提交支付!");
        }
        $body = "订单{$order_item->order_sn}提交微信支付";
        $order_num = $order_item->order_sn;
        $total_fee = $order_item->order_amount * 100;
        $spbill_create_ip = $this->request->ip();

        $data = [
            "account_id" => $this->account_id,
            "pay_type" => 3,
            "pay_no" => $order_num,
            "pay_money" => $order_item->order_amount,
            "remark" => "订单($order_item->order_sn)微信支付"
        ];
        Db::startTrans();
        $payment = AccountPayment::create($data);
        if (!$payment) {
            Db::rollback();
            $this->error("提交订单出错1!");
        }
        $order_item->payment_id = $payment->id;
        $result = $order_item->save();
        if (!$result) {
            Db::rollback();
            $this->error("提交订单出错2!");
        }
        Db::commit();
        $pay = PayManagement::instance();
        $params = array(
            'openid' => $openid,
            'body' => $body,
            'out_trade_no' => $order_num,
            'spbill_create_ip' => $spbill_create_ip,
            'total_fee' => $total_fee,
            'attach' => 5
        );

        $res = $pay->unifiedOrder($params);

        $jsApiParameters = $pay->getJsPayParameters($res['prepay_id']);
        $this->success("提交订单成功!", null, $jsApiParameters);
//        $this->assign('jsApiParameters', json_encode($jsApiParameters));
//        $this->assign('order', $order);
//        return view();
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="取消订单">
    public function cancel_order()
    {
        $order_id = input("order_id");

        $order = ShopOrder::get(["id" => $order_id, "account_id" => $this->account_id]);
        if (!$order) {
            $this->error("获取订单错误1!");
        }
        if ($order->flag_status['value'] == 1) {
            $this->error("已配送的订单不能取消!");
        }
        if ($order->flag_status['value'] == 4) {
            $this->error("此订单已取消!");
        }
//        if ($order->payment_id == 0 && $order->flag_delivery == 0) {
//            $this->error("正在支付的订单不能取消!");
//        }
        Db::startTrans();

        if ($order->flag_pay == 1 && $order->flag_delivery == 0) {
            $data = array(
                'account_id' => $this->account_id, 'money' => $order['order_amount'], 'remark' => "订单{$order->order_sn}-取消退款"
            );
            $res = AccountBill::create($data);
            if (!$res) {
                Db::rollback();
                $this->error("订单取消出错2!");
            }
            $ac = new Account();
            //更改账户余额
            $res2 = $ac->where(['id' => $this->account_id])->setInc('money', $order['order_amount']);
            if (!$res2) {
                Db::rollback();
                $this->error("订单取消出错3！");
            }
        }
        $result = $order->where(["id" => $order_id, "account_id" => $this->account_id])->setField(["flag_status" => 4]);
        if (!$result) {
            Db::rollback();
            $this->error("取消订单出错4!");
        }
        $result = ShopOrderItem::update(["flag_status" => 4], ["order_id" => $order_id, "account_id" => $this->account_id]);
        if (!$result) {
            Db::rollback();
            $this->error("操作订单出错4!");
        }
        Db::commit();
        if ($order->flag_pay == 1) {
            $this->success("取消订单成功,钱款已返回您的账户!");
        }
        $this->success("取消订单成功!");
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="用户确认收货">
    public function take_order()
    {
        $order_id = input("order_id");
        $info = ShopOrder::get($order_id);
        if ($info) {
            $info = $info->getData();
        }
        if ($info["flag_status"]==7){
            $this->error("此订单已确认收货!");
        }
        if ($info["flag_pay"] == 0 && $info["flag_delivery"] == 0) {
            $this->error("此订单未付款!");
        }
        if ($info["flag_status"] == 0) {
            $this->error("此订单未未配送!");
        }
        if ($info["flag_status"] == 2) {
            $this->error("此订单已申请取消!");
        }
        if ($info["flag_status"] == 3 || $info["flag_status"] == 4) {
            $this->error("此订单已取消!");
        }
        if (in_array($info["flag_status"], [1, 6])) {
            $take_time = time();
            Db::startTrans();
            $result = ShopOrder::update(["flag_pay" => 1, "flag_status" => 7, "take_time" => $take_time], ["id" => $order_id]);
            if (!$result) {
                Db::rollback();
                $this->error("操作订单出错1!");
            }
            $mo = new ShopOrderItem();
//          $payment_ids = $mo->where(["order_id" => $order_id])->column("payment_id");
            $result = AccountPayment::update(["flag_pay" => 1], ["id" =>$info["payment_id"]]);
            if (!$result) {
                Db::rollback();
                $this->error("操作订单出错3!");
            }
            $result = ShopOrderItem::update(["flag_pay" => 1, "flag_status" => 7, "take_time" => $take_time], ["order_id" => $order_id]);
            if (!$result) {
                Db::rollback();
                $this->error("操作订单出错4!");
            }
            Db::commit();
            //消息模板
//            $goods = [];
//            $oauth = AccountWechat::get(['account_id' => $info["delivery_account_id"]]);
//            $openid = $oauth['openid'];
//            $shopOrderGoods = new ShopOrderGoods();
//            $shopGoods = new ShopGoods();
//            $orderItmeIds = $mo->where(["order_id" => $order_id])->column("id");
//            $goods_id = $shopOrderGoods->where(["order_item_id" => ["in", $orderItmeIds]])->column("goods_id");
//            $gn = $shopGoods->where(["id" => ["in", $goods_id]])->column("name");
//            $goods = array_merge($goods, $gn);

           // send_msg::user_take_msg($openid, $info, $goods);

            $this->success("操作成功!");
        } else {
            $this->error("操作订单出错2!");
        }
    }
    // </editor-fold>
}